import { OneModal } from '@/components/one-ui';
import React, { Ref, useRef, useState, useMemo, useEffect, useContext } from 'react';
import { IOneModalRef } from '@/pages/type';
import { Button, Spin, Space, Form, message } from 'antd';
import { getTenantID, onCloseModalCommon } from '@/utils';
import cls from 'classnames';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import TableFormView from './TableFormView';
import { AcquisitionManageContext, IAcquisitionActionEnum } from '../mconfig';
import { filterTimeProperties, submitTimeProperties } from '@/pages/AssetManage/Acommon';
import _ from 'lodash';
import { ILoadMapTypeAll } from '@/common';
import { getEnterServiceTranslate } from '../services';

export const SelectAssetView: React.FC<any> = ({ curRes, onClose, type, onCloseAll, editMaterialRun, modalLoading }) => {
  const {
    materielList, // 资产列表list
    // 表格数据及参数
    selectFormInfo, // 表单数据
    selectRecordId, // 当前行的id
    acquisitionDispatch,
  } = useContext(AcquisitionManageContext);

  const prefix = 'material-upload-';

  /** 弹框的ref */
  const uploadModalRefs: Ref<IOneModalRef> = useRef(null);

  /** 引用的form表单 */
  const [assetForm] = Form.useForm();

  /** 页面刷新状态 */
  const [loading, setLoading] = useState<boolean>(false);

  /** 传给表单的数据 */
  const [currentData, setCurrentData] = useState({ pageType: '', record: {} });

  const { EnterServiceManageRun } = getEnterServiceTranslate();

  /** 修改页面刷新状态 */
  const changeLoading = (flag: boolean) => {
    setLoading(flag);
  };

  useEffect(() => {
    if (type == 'detail' || type == 'edit') {
      let obj: any = JSON.parse(JSON.stringify(selectFormInfo));
      obj = {
        ...obj,
        ...obj?.assetjson,
        obtainType: obj?.obtainType,
        obtainTypeName: obj?.obtainTypeName,
      };
      const newFormInfo = filterTimeProperties(obj);
      // 单位会计科目默认显示 固定资产
      newFormInfo.ledgerAccount = '100124441000';
      newFormInfo.assetState = '100124031000';
      newFormInfo.scrapRate = newFormInfo.scrapRate ?? 0;
      newFormInfo.depreciationMoney = newFormInfo.depreciationMoney ?? 0;
      newFormInfo.providedDepreciation = newFormInfo.providedDepreciation ?? 0;
      newFormInfo.approvedBy = newFormInfo.approvedBy ?? `${getTenantID()}${ILoadMapTypeAll.ASSET_APPROVEDBY}1003`;
      // 入库进去的隐藏使用人，使用部门
      newFormInfo.formAddFlag = true;
      setCurrentData({
        pageType: type,
        record: newFormInfo,
      });
    }
  }, [type, selectFormInfo, materielList]);

  /**点击取消方法*/
  const onUploadCancel = () => {
    onCloseModalCommon(uploadModalRefs);
    // onCloseAll();
  };

  // 保存表单数据
  const handleConfirm = () => {
    // 表单校验
    assetForm.validateFields().then(
      async (values: any) => {
        values.assetType = values.assetClass;
        // const values = assetForm.getFieldsValue(true);
        const processFormData: any = submitTimeProperties(values);
        let newMaterielList: any = JSON.parse(JSON.stringify(materielList));
        // 遍历list  根据id筛选当前数据进行更新
        let editMaterielList = newMaterielList.filter((v) => (v.id || v.rowId) == selectRecordId);
        if (editMaterielList.length > 0) {
          let param = {
            ...editMaterielList[0],
            ...values,
            assetName: values.assetName, // 资产名称
            materialCode: values.materialCode, // 物资编号
            assetClass: values.assetClass, // 物资分类
            ownership: values.ownership || 100124411000, // 产权
            brandType: values.brandType, // 品牌
            paramsInfo: values.paramsInfo, // 规格型号
            quantityOrArea: values.quantityOrArea, // 数量
            unitOfMeasurement: values.unitOfMeasurement, // 计量单位
            assetValue: values.assetValue, // 单价
            sharing: values.sharing || 0, // 是否共享公用
            totalValue: _.round(_.multiply(values.quantityOrArea, values.quantityOrArea), 4), // 总价
            // 标识弹窗form表单填写完成
            formResolveFlag: true,
            assetjson: {
              ...editMaterielList[0].assetjson,
              ...processFormData,
            },
          };

          delete param?.assetjson?.['assetjson'];
          let resData: any = await EnterServiceManageRun(param);
          param = {
            ...param,
            ...resData?.obj?.assetjson,
          };
          if (selectFormInfo?.formAddFlag) {
            newMaterielList = newMaterielList.map((v) => {
              if ((v.id || v.rowId) == selectRecordId) {
                let item = {
                  ...v,
                  ...param,
                  assetjson: {
                    ...param,
                  },
                };
                return item;
              } else {
                return v;
              }
            });
          } else {
            await editMaterialRun(param);
          }
        }
        if (selectFormInfo?.formAddFlag) {
          acquisitionDispatch({
            type: IAcquisitionActionEnum.SELECT_MATERIEL,
            payload: newMaterielList,
          });
        }
        onCloseModalCommon(uploadModalRefs);
      },
      () => {
        message?.warn('请检查填写内容是否有误或漏填！');
      },
    );
  };

  /** 底部按钮 */
  const footerModal = useMemo(() => {
    return (
      <div className={cls(prefix + 'footer')}>
        <Space>
          <Button key="back" onClick={onUploadCancel}>
            关闭
          </Button>
          {type != 'detail' && (
            <>
              <Button type="primary" onClick={handleConfirm}>
                确认
              </Button>
            </>
          )}
        </Space>
      </div>
    );
  }, [curRes]);

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={uploadModalRefs}
        title={'资产信息'}
        onCancel={onClose}
        // onOk={onUploadOK}
        footer={footerModal}
        width={document.body.clientWidth * 0.85}
        bodyStyle={{ height: document.body.clientHeight * 0.75, padding: '5px 10px' }}
        centered
      >
        <Spin spinning={loading || modalLoading}>
          <div className={'material-upload'} style={{ padding: '0 30px' }}>
            <div className={cls(prefix + 'content')} style={{ height: '100%', paddingBottom: '10px', paddingTop: '10px' }}>
              <TableFormView formName={assetForm} locationProps={currentData} currentType={selectFormInfo.tempSelectType} changeLoading={changeLoading} />
            </div>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};

/**点击确定方法*/
// const onUploadOK = () => {
//   onCloseModalCommon(uploadModalRefs);
// };

// 点击下一步或者标签 切换
// const handleNextClick = () => {
//   // 切换tab
//   setCurrent(1);
//   // 修改勾选的选项
//   acquisitionDispatch({
//     type: IAcquisitionActionEnum.SELECT_ASSET_INFO,
//     payload: assetTypeData,
//   });
//   // form表单回显
//   assetForm.setFieldsValue({
//     ledgerAccount: assetTypeData.assetType,
//   });
// };

{
  /* {current === 0 && (
            <Button
              onClick={() => {
                if (assetTypeData.assetType) {
                  handleNextClick();
                } else {
                  message.warning('请选择资产类型');
                }
              }}
            >
              下一步
            </Button>
          )} */
}
{
  /* {type != 'detail' && current === 1 && (
            <>
              <Button type="primary" onClick={handleConfirm}>
                确认
              </Button>
            </>
          )} */
}

{
  /* <div className={cls(prefix + 'step')}>
              <Steps current={current} size={'small'} items={steps} onChange={handleChangeSteps} />
            </div> */
}

{
  /* {current === 0 && <AssetTypeView current={current} selectTypeNum={assetTypeData.number} changeFun={handleChangeAsset} />} */
}
{
  /* locationProps 页面信息  包含数据 */
}
{
  /* {current === 1 && <TableFormView formName={assetForm} locationProps={currentData} currentType={selectFormInfo.assetType} />} */
}

/**改变步骤条 */
// const handleChangeSteps = (current: number) => {
//   if (current === 0) {
//     setCurrent(0);
//   } else if (current === 1) {
//     if (assetTypeData.assetType) {
//       handleNextClick();
//     } else {
//       message.warning('请选择资产类型');
//     }
//   }
// };

// const handleChangeAsset = (assetType: string, num: number) => {
//   if (type == 'detail') return;
//   setAssetTypeData({
//     assetType,
//     number: num,
//   });
// };
